<?php

namespace app\controller;

use app\manager\RedisInstance;
use app\model\RegisterModel;
use app\model\UserModel;
use app\Request;
use app\service\LoginService;
use app\util\UserContext;
use mysql_xdevapi\SqlStatementResult;
use think\facade\Db;
use think\facade\View;

class User extends Base
{
    private $loginService;
    public function __construct()
    {
        $this->loginService = new LoginService();
    }

    // 用类保存信息 CheckToken1
//    public function info(Request $request){
//        $uid = UserContext::get();
//        $user = UserModel::seletUserById($uid);
//        View::assign('user',$user);
//        return View::fetch('info');
//    }
    //用session保存 CheckToken2
    public function info(Request $request){
        $uid = $_SESSION['uid'];
        $user = UserModel::seletUserById($uid);
        View::assign('user',$user);
        //$this->assign('user', $user);
        return View::fetch('info');
    }

    // 保存redis
//    public function login(Request  $request){
//        p($_SERVER);
//        if ($request->isPost()){
//            $phone = $request->all('account');
//            $pwd = $request->all('password');
//            $user = RegisterModel::seletByPhone($phone);
//            if (empty($user)){
//                echo '账号错误';
//                return View::fetch('login');
//            }
//            $newPwd = \md5($pwd);
//            if ($user['pwd']!=$newPwd){
////                return View::fetch('login');
//            }
//            $token = \md5('login:'.$phone);
//            RedisInstance::set($token,$user['id']);
//           // setcookie('token',$token);
//            cookie('token',$token,3600);
//            return redirect("/user/index");
//        }
//        return View::fetch('login');
//    }

// session登录
    public function login(Request  $request){

        if ($request->isPost()){
            $phone = $request->all('account');
            $pwd = $request->all('password');
            $user = RegisterModel::seletByPhone($phone);
            View::assign('msg','');

            if (empty($user)){
               // echo '账号错误';
                //return View::fetch('login');
                return $this->viewError('/user/login','账号错误');
            }
            $newPwd = \md5($pwd);
            if ($user['pwd']!=$newPwd){
                //return View::fetch('login');
                return $this->viewError('/user/login','密码错误');
            }
            $_SESSION['uid']=$user['id'];
            View::assign('msg','登录成功');
            //return View::fetch('transfer');

            return $this->viewSuccess('/user/index','登录成功');
        }
        return View::fetch('login');
    }
    /**
     * @return bool
     */
    public function index()
    {
        return  View::fetch('index');

    }
}